
<template>
  <div class="edit-down-table">
    <vxe-pulldown class="edit-down-pulldown" ref="xDown" transfer>
      <template>
        <vxe-input class="edit-down-input" v-model="textValue" suffix-icon="fa fa-caret-down" @change="changeEvent" @keyup="keyupEvent" @click="clickEvent" @focus="focusEvent"  @suffix-click="suffixClick" @blur="blurEvent"></vxe-input>
      </template>
      <template v-slot:dropdown>
        <div class="edit-down-wrapper">
          <vxe-grid
            highlight-hover-row
            highlight-current-row
            auto-resize
            height="auto"
            ref="grid"
            row-id="id"
            :loading="loading"
            :data="tableData"
            :columns="tableColumns"
            :pager-config="tablePage"
            :cell-style="cellStyle"
            @cell-click="selectEvent"
            @page-change="pageChangeEvent">
          </vxe-grid>
        </div>
      </template>
    </vxe-pulldown>
  </div>
</template>

<script>
export default {
  name: 'MatrDownTable',
  props: {
    params: Object,
    renderOpts: Object
  },
  data() {
    return {
      row: null,
      column: null,
      loading: false,
      changeFetchData: true,
      perQueryWrapper: null,
      textValue: '',
      textOldValue: '',
      queryUrl: '/base/matr/pageForSelect',
      tableData: [],
      currentRow: {},
      tableColumns: [
        { type: 'seq', width: 40},
        { title: '品名', field: 'name', search: true},
        { title: '品规',  field: 'spec', width: 200, search: true},
        { title: '厂商名称',  field: 'mfgName', width: 250},
        { title: '单品单位',  field: 'skuUnit', width: 130},
        { title: '单品单价',  field: 'skuPrice', width: 130}
      ],
      tablePage: {
        border: true,
        autoHidden: true,
        currentPage: 1,
        pageSize: 20,
        pageSizes: [20, 50, 100, 200],
        total: 0,
        layouts: ['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']
      }
    }
  },
  watch: {
    // params() {
    //   this.load()
    // }
  },
  mounted() {
    this.load()
  },
  methods: {
    load() {
      const {row, column } = this.params //行、列数据
      this.row = row
      this.column = column
      const { props = {} } = this.renderOpts
      this.tableColumns = (props.tableColumns && props.tableColumns[column.property]) || this.tableColumns
      this.textValue = row[column.property]
      this.textOldValue = this.textValue
      let tableQueries = props.tableQueries && props.tableQueries[column.property]
      if (tableQueries) {
        this.perQueryWrapper = tableQueries.wrapper
        this.queryUrl = tableQueries.queryUrl || this.queryUrl
      }
      this.fetchData()
    },
    fetchData() {
      let wrapper = this.$newWrapper()
      if (this.perQueryWrapper) {
        wrapper.from(this.perQueryWrapper)
      }
      if (this.strings.isNotBlank(this.textValue) && this.textValue != this.textOldValue) {
        this.tableColumns.filter(column => column.search).forEach(column => {
          wrapper.orlike(column.field, this.textValue)
        })
      }

      let params = {
        queryString: JSON.stringify(wrapper.queryConditions),
        currentPage: this.tablePage.currentPage,
        rowsPerPage: this.tablePage.pageSize,
        keyword: this.textValue ? this.textValue : null
      }

      //存到vuex中，防止多次调用后端
      let currentMatrs = this.utils.getCurrentMatrs()

      const { props = {} } = this.renderOpts
      let attr = props.dataview.$attrs
      let loadEvery = false
      if (attr.propLoadEvery != undefined && attr.propLoadEvery)  loadEvery = attr.propLoadEvery

      if (!loadEvery  && currentMatrs && currentMatrs.queryParams && this.utils.paramsEquals(params, currentMatrs.queryParams) && this.queryUrl == currentMatrs.queryUrl) {
        this.tableData = currentMatrs.matrs
        this.tablePage.total = currentMatrs.total
        this.setCurrentRow()
        return
      }
      this.$ajax.get(this.queryUrl, {params}).then(resp => {
        this.tableData = resp.data
        this.tablePage.total = parseInt(resp.count == null ? resp.data.length : resp.count, 10)
        this.setCurrentRow()
        let currentMatrs = {queryParams: params, matrs: resp.data, total: this.tablePage.total, queryUrl: this.queryUrl}
        this.$store.dispatch('setCurrentMatrs', currentMatrs)
      })
    },
    setCurrentRow() {
      if (this.row.matrId) {
        this.currentRow = this.tableData.find(item => item.id == this.row.matrId)
        this.currentRow && this.$refs.grid.setCurrentRow(this.currentRow) && this.$refs.grid.scrollToRow(this.currentRow)
      }
    },
    focusEvent() {
      if (!this.row.matrId) {
        this.$refs.xDown.showPanel()
      }
    },
    blurEvent() {
      if (this.currentRow) {
        this.row.matrName = this.currentRow.name
      }
    },
    changeEvent() {
      if (this.changeFetchData) {
        this.changeFetchData = false
        setTimeout(() => this.changeFetchData = true, 800)
        this.fetchData()
      }
    },
    clickEvent() {
      const { props = {} } = this.renderOpts
      let attr = props.dataview.$attrs
      let loadEvery = false
      if (attr.propLoadEvery != undefined && attr.propLoadEvery)  loadEvery = attr.propLoadEvery
      if (loadEvery) {
        this.changeFetchData = true
        this.load()
      }
      this.$refs.xDown.showPanel()
    },
    keyupEvent({ $event }) { // 根据输入筛选
      $event.stopPropagation()
      this.$refs.xDown.showPanel()
      const { row, column } = this
      const { keyCode } = $event
      const cellValue = row[column.property]

      let {grid} = this.$refs
      let selectedRow = grid.getCurrentRecord()
      let rowIndex = grid.getRowIndex(selectedRow)
      if (keyCode == 38) {
        if (rowIndex <= grid.data.length) {
          grid.setCurrentRow(grid.getData(rowIndex - 1))
          grid.scrollToRow(grid.getData(rowIndex - 1))
        }
      } else if (keyCode == 40) {
        if (rowIndex >= -1) {
          grid.setCurrentRow(grid.getData(rowIndex + 1))
          grid.scrollToRow(grid.getData(rowIndex + 1))
        }
      } else if (keyCode == 13) {
        let params = {
          row: selectedRow
        }
        this.selectEvent(params)
      }
    },
    suffixClick() {
      this.$refs.xDown.togglePanel()
    },
    pageChangeEvent({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.fetchData()
    },
    selectEvent(params) { //选择耗材事件，选择后调用适用房的matrChangeEvent方法来解决
      const { renderOpts, row, column } = this
      const { props = {} } = renderOpts
      this.$set(column, 'selectRow', params.row)
      this.currentRow = params.row
      this.textValue = params.row.name
      // props.dataview.$emit('matrChangeEvent', row, params.row)
      props.dataview.$emit('select-change', {row, column})
      this.$refs.xDown.hidePanel()
    },
    cellStyle({ row, rowIndex, column, columnIndex }) {
      if (column.property === 'stockCount') {
        // eslint-disable-next-line radix
        if (parseInt(row.stockCount) <= 0) {
          return {
            color: 'red'
          }
        }
      }
      if (column.property === 'canUseCount') {
        // eslint-disable-next-line radix
        if (parseInt(row.canUseCount) <= 0) {
          return {
            color: 'red'
          }
        }
      }
    }
  }
}
</script>

<style lang="scss">
  .vxe-pulldown--panel {
    z-index: 10000 !important;
  }

  .edit-down-pulldown {
    width: 100%;
  }
  .edit-down-wrapper {
    width: 65vw !important;
    height: 500px;
    background-color: #fff;
    border: 1px solid #dcdfe6;
    box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
  }
</style>
